/**
 ****************************************************************************************
 *
 * @file main.c
 *
 * @brief Main loop of the application.
 *
 * Copyright (C) Quintic 2009-2012
 *
 * $Rev: $
 *
 ****************************************************************************************
 */

/*
 * INCLUDES
 ****************************************************************************************
 */

#include "LPC17xx.h"
#include "uart.h"
#include "app_env.h"

/*
 * FUNCTIONS
 ****************************************************************************************
 */

/**
 ****************************************************************************************
 * @brief App init function.
 *
 * This function is used to setup  and MENU UART.
 ****************************************************************************************
 */
static void AppInit(void)
{
    // ACI UART
    uart_init(QN_HCI_UART, USARTx_CLK(0), UART_9600);
    uart_tx_enable(QN_HCI_UART, MASK_ENABLE);
    uart_rx_enable(QN_HCI_UART, MASK_ENABLE);

    // Menu UART
    uart_init(QN_DEBUG_UART, USARTx_CLK(0), UART_9600);
    uart_tx_enable(QN_DEBUG_UART, MASK_ENABLE);
    uart_rx_enable(QN_DEBUG_UART, MASK_ENABLE);

    // Application
    app_init();
}

/**
 ****************************************************************************************
 * @brief Application schedule function.
 *
 * This function is called right after the booting process has completed.
 ****************************************************************************************
 */
static void AppSchedule(void)
{
    while (1)
    {
        // Check debug uart input
        if (app_env.input_len != 0)
        {
            app_menu_hdl();
            app_env.input_len = 0;
        }

        // Check aci uart input
        if (false == eaci_msg_que_is_empty(&app_env.msg_que))
        {
            struct eaci_msg *msg = (struct eaci_msg *)eaci_msg_que_pop(&app_env.msg_que);
            if (msg)
            {
                app_eaci_msg_hdl(msg->msg_type, msg->msg_id, msg->param_len, msg->param);
                MSG_FREE(msg);
            }
        }
        
        // Check for sleep have to be done with interrupt disabled
        GLOBAL_INT_DISABLE();
        // check sleep mode
        GLOBAL_INT_RESTORE();
    }
}

/**
 ****************************************************************************************
 * @brief main function.
 *
 * This function is called right after the booting process has completed.
 ****************************************************************************************
 */
int main(void)
{
    // System
    SystemInit();

    // App
    AppInit();
    
    // Schedule
    GLOBAL_INT_START();
    AppSchedule();
    GLOBAL_INT_STOP();
}

